<?php

namespace PhpYes\Com;

final class CsvGenerator
{
    /**
     * @param array $data - [[colo1,col2,...], [colo1,col2,...], ...]
     * @return string
     */
    public static function gen($data)
    {
        if (empty($data) || empty($data[0]) || !is_array($data[0])) {
            return '';
        }
        $colCnt = count($data[0]);
        $csv = '';
        foreach ($data as $row) {
            for ($i = 0; $i < $colCnt; $i++) {
                if ($i > 0) {
                    $glue = ',';
                } else {
                    if (empty($csv)) {
                        $glue = '';
                    } else {
                        $glue = "\r\n";
                    }
                }
                $csv .= $glue;
                $cell = isset($row[$i]) ? strval($row[$i]) : '';
                if (empty($cell)) {
                    $csv .= $cell;
                } else {
                    $newCell = '';
                    $isNeedQuote = false;
                    $len = strlen($cell);
                    for ($j = 0; $j < $len; $j++) {
                        $c = $cell[$j];
                        if ($c == '"') {
                            $isNeedQuote = true;
                            $newCell .= '""';
                        } else {
                            if ($c == ',' || $c == "\r" || $c == "\n") {
                                $isNeedQuote = true;
                            }
                            $newCell .= $c;
                        }
                    }
                    if ($isNeedQuote) {
                        $csv .= '"' . $newCell . '"';
                    } else {
                        $csv .= $newCell;
                    }
                }
            }
        }

        return $csv;
    }

}